<template>
  <div class="share">
    <div class="top">【长按图片保存或发给好友！】</div>
    <qriously id="qrcode" style="display: none" :value="initQCode" :size="138" ref="qrcodeimg" />
    <img :src="imgUrl" alt class="img" />
    <div class="ctx" ref="imageWrapper">
      <img @load="loadImg" src="@/assets/2_246_46443_share.png" alt class="bg" />
      <img @load="loadImg" :src="headimgurl" alt class="head" />
      <img @load="loadImg" :src="imgSrc" alt class="qr" />
    </div>
    <div class="btn">长按上方图片发送给好友</div>
  </div>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import html2canvas from "html2canvas";
import store from "@/store";
import { getPoster } from "@/api";
const token: string = store.state.userToken;
@Component
export default class Share extends Vue {
  initQCode: string = "";
  imgSrc: string = "";
  imgUrl: string = "";
  interval: any;
  headimgurl: string =
    "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKOt58dj31Tk1Oib0qyTehjkzoWDrT72OzPkykA6Xueicn1Dqwe2pw7icfS1iapupV9fcZXaWeuIsdHyA/132";
  img: string = "";
  loadCount: number = 0;

  created() {
    this._getPoster();
    this.$nextTick(() => {
      this.initQCode =
        "http://www.liubd.cn/api/wechat/authorize?sourceUserId=" + token;
      var canvas1: any = document.querySelectorAll("#qrcode")[0];
      this.imgSrc = (this as any).$refs.qrcodeimg.$refs.qrcode.toDataURL(
        "image/png"
      );
    });
  }
  loadImg() {
    this.loadCount++;
    if (this.loadCount == 3) {
      this.toImg();
    }
  }
  _getPoster() {
    getPoster().then(res => {
      console.log("res", res);
      this.headimgurl = res.data.headimgurl;
    });
  }
  async toImg() {
    const opts = {
      useCORS: true,
      backgroundColor: null
    };
    try {
      await html2canvas((this as any).$refs.imageWrapper, opts as any).then(
        (canvas: any) => {
          let dataURL = canvas.toDataURL("image/png");
          this.imgUrl = dataURL;
        }
      );
    } catch (error) {
      console.log("error", error);
    }
  }
}
</script>

<style lang="less" scoped>
.btn {
  position: fixed;
  bottom: 8px;
  left: 8px;
  right: 8px;
  height: 60px;
  border-radius: 40px;
  background-color: #fdd559;
  line-height: 60px;
  text-align: center;
  font-size: 14px;
  font-weight: 700;
  color: #333;
}
.img {
  width: 350px;
  margin-top: 50px;
  margin-bottom: 70px;
}
.ctx {
  width: 350px;
  margin: 0 auto;
  position: fixed;
  left: -1800px;
  .head {
    position: absolute;
    width: 50px;
    left: 30px;
    bottom: 50px;
  }
  .qr {
    width: 70px;
    position: absolute;
    bottom: 45px;
    left: 150px;
  }
  .bg {
    width: 100%;
  }
}
canvas {
  display: none;
}
.top {
  position: fixed;
  background-color: #fff;
  top: 0;
  font-size: 16px;
  color: red;
  text-align: center;
  padding-top: 10px;
  padding-bottom: 10px;
  left: 0;
  right: 0;
}
</style>
